package com.yyfax.ph.base;


import android.content.Intent;
import android.widget.Button;
import android.widget.CheckBox;
import com.yyfax.common.form.LoginLayout;
import com.yyfax.ph.R;
import com.yyfax.ph.personal.authority.login.LoginActivity;
import com.yyfax.ph.main.MainActivity;
import com.yyfax.ph.personal.authority.gesture.ModifyGesturesActivity;
import org.junit.Assert;
import org.robolectric.Robolectric;
import org.robolectric.Shadows;
import org.robolectric.TestLifecycleApplication;
import org.robolectric.android.controller.ActivityController;
import org.robolectric.shadows.ShadowActivity;

import java.lang.reflect.Method;

/**
 * Created by HenryZhang on 2017/6/7.<br>
 * Copyright © 2017 www.yylending.com. All Rights Reserved.<br><br>
 */
public class LifecycleApplication extends YJPH implements TestLifecycleApplication {

	@Override
	public void beforeTest(Method method) {
		BasicTestRunner.asyncToSync();
		BasicTestRunner.printLog();
	}

	@Override
	public void prepareTest(Object test) {
		ActivityController<MainActivity> mActivityController = Robolectric.buildActivity(MainActivity.class);
		MainActivity aty = mActivityController.create().visible().get();
		mActivityController.start().resume();

		ActivityController<LoginActivity> mLoginActivityController = Robolectric.buildActivity(LoginActivity.class);
		LoginActivity mLoginActivity = mLoginActivityController.create().start().get();
		LoginLayout mPhoneLayout = (LoginLayout) mLoginActivity.findViewById(R.id.login_layout);
		LoginLayout mPasswordLayout = (LoginLayout) mLoginActivity.findViewById(R.id.password_layout);
		CheckBox mAgreeBox = (CheckBox) mLoginActivity.findViewById(R.id.check_agreement_box);
		Button mLoginBtn = (Button) mLoginActivity.findViewById(R.id.login_tv);
		/***
		 * 正确的用户名和密码
		 */
		mPhoneLayout.setText("13163764627");
		mPasswordLayout.setText("a123456");
		mAgreeBox.setChecked(true);
		mLoginBtn.performClick();
		boolean isFirstLogin = YJPH.getInstance().getPreferenceManager().isFirstLogin(true);
		Assert.assertFalse(isFirstLogin);
		/***
		 * 如果是第一次登陆IsFirstLogin默认为true。登陆成功之后 IsFirstLogin会被设置为false，跳转到手势密码设置页面；
		 */
		if (!isFirstLogin) {
			Intent expectedIntent = new Intent(mLoginActivity, ModifyGesturesActivity.class);
			ShadowActivity shadowActivity = Shadows.shadowOf(mLoginActivity);
			Intent actualIntent = shadowActivity.getNextStartedActivity();
			Assert.assertNotNull(actualIntent);
			Assert.assertEquals(expectedIntent.getComponent().getClassName(), actualIntent.getComponent().getClassName());
		} else {
			Intent expectedIntent = new Intent(mLoginActivity, MainActivity.class);
			ShadowActivity shadowActivity = Shadows.shadowOf(mLoginActivity);
			Intent actualIntent = shadowActivity.getNextStartedActivity();
			Assert.assertNotNull(actualIntent);
			Assert.assertEquals(expectedIntent.getComponent().getClassName(), actualIntent.getComponent().getClassName());
		}
	}

	@Override
	public void afterTest(Method method) {
	}
}
